import React, { useState, useRef } from 'react';
import { Button, Upload, message, Modal, Alert, Descriptions, Space, Divider } from 'antd';
import { 
  DownloadOutlined, 
  UploadOutlined, 
  FileTextOutlined,
  ExclamationCircleOutlined,
  CheckCircleOutlined
} from '@ant-design/icons';
import { ImportResult, ExportedConfig } from '../types/index';
import { ServiceManager } from '../services/ServiceManager';

interface ConfigManagerProps {
  onConfigImported?: (result: ImportResult) => void;
  disabled?: boolean;
}

export const ConfigManager: React.FC<ConfigManagerProps> = ({
  onConfigImported,
  disabled = false
}) => {
  const [isExporting, setIsExporting] = useState(false);
  const [isImporting, setIsImporting] = useState(false);
  const [importPreview, setImportPreview] = useState<{
    visible: boolean;
    data: ExportedConfig | null;
    file: File | null;
    mergeMode: boolean;
  }>({
    visible: false,
    data: null,
    file: null,
    mergeMode: false
  });

  const fileInputRef = useRef<HTMLInputElement>(null);
  const serviceManager = ServiceManager.getInstance();

  // 导出配置
  const handleExport = async () => {
    setIsExporting(true);
    
    try {
      await serviceManager.importExportService.exportConfig();
      message.success('配置导出成功！');
    } catch (error) {
      console.error('导出配置失败:', error);
      message.error(`导出失败: ${error instanceof Error ? error.message : '未知错误'}`);
    } finally {
      setIsExporting(false);
    }
  };

  // 处理文件选择
  const handleFileSelect = async (file: File) => {
    if (!file.name.endsWith('.json')) {
      message.error('请选择 JSON 格式的配置文件');
      return false;
    }

    try {
      const content = await readFileContent(file);
      const preview = serviceManager.importExportService.generateConfigPreview(content);
      
      if (!preview.isValid) {
        message.error(`配置文件无效: ${preview.error}`);
        return false;
      }

      // 获取完整的配置数据用于预览
      const validation = serviceManager.importExportService.validateConfigFile(content);
      if (validation.isValid && validation.data) {
        setImportPreview({
          visible: true,
          data: validation.data,
          file,
          mergeMode: false
        });
      }
    } catch (error) {
      message.error('读取文件失败');
      return false;
    }

    return false; // 阻止自动上传
  };

  // 执行导入
  const executeImport = async (mergeMode: boolean) => {
    if (!importPreview.file) return;

    setIsImporting(true);
    
    try {
      const result = await serviceManager.importExportService.importConfig(
        importPreview.file,
        mergeMode
      );
      
      if (result.success) {
        message.success(
          `配置导入成功！导入了 ${result.importedKeys.length} 项配置${
            result.skippedKeys.length > 0 ? `，跳过了 ${result.skippedKeys.length} 项` : ''
          }`
        );
        onConfigImported?.(result);
      } else {
        message.error(`导入失败: ${result.errors?.join(', ')}`);
      }
      
      setImportPreview({ visible: false, data: null, file: null, mergeMode: false });
    } catch (error) {
      console.error('导入配置失败:', error);
      message.error(`导入失败: ${error instanceof Error ? error.message : '未知错误'}`);
    } finally {
      setIsImporting(false);
    }
  };

  // 读取文件内容
  const readFileContent = (file: File): Promise<string> => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => resolve(reader.result as string);
      reader.onerror = () => reject(new Error('文件读取失败'));
      reader.readAsText(file, 'utf-8');
    });
  };

  // 渲染预览模态框
  const renderPreviewModal = () => {
    const { visible, data } = importPreview;
    
    return (
      <Modal
        title="配置导入预览"
        open={visible}
        onCancel={() => setImportPreview({ visible: false, data: null, file: null, mergeMode: false })}
        footer={[
          <Button 
            key="cancel" 
            onClick={() => setImportPreview({ visible: false, data: null, file: null, mergeMode: false })}
          >
            取消
          </Button>,
          <Button
            key="merge"
            onClick={() => executeImport(true)}
            loading={isImporting}
            disabled={!data}
          >
            合并导入
          </Button>,
          <Button
            key="replace"
            type="primary"
            onClick={() => executeImport(false)}
            loading={isImporting}
            disabled={!data}
          >
            覆盖导入
          </Button>
        ]}
        width={600}
      >
        {data && (
          <div className="space-y-4">
            <Alert
              message="配置文件预览"
              description="请确认以下配置信息是否正确，然后选择导入模式"
              type="info"
              showIcon
            />

            <Descriptions bordered size="small" column={1}>
              <Descriptions.Item label="文件版本">
                {data.version}
              </Descriptions.Item>
              <Descriptions.Item label="导出时间">
                {new Date(data.exportDate).toLocaleString('zh-CN')}
              </Descriptions.Item>
              <Descriptions.Item label="LLM 供应商">
                <span className="font-medium">{data.config.llm}</span>
              </Descriptions.Item>
              <Descriptions.Item label="模型名称">
                <span className="font-medium">{data.config.modelName}</span>
              </Descriptions.Item>
              <Descriptions.Item label="API 地址">
                {data.config.options.baseURL}
              </Descriptions.Item>
              <Descriptions.Item label="API Key">
                <span className="font-mono text-sm">
                  {data.config.apiKey.substring(0, 8)}...{data.config.apiKey.slice(-4)}
                </span>
              </Descriptions.Item>
              {data.metadata?.extensionVersion && (
                <Descriptions.Item label="扩展版本">
                  {data.metadata.extensionVersion}
                </Descriptions.Item>
              )}
            </Descriptions>

            <Divider />

            <div className="space-y-2">
              <h4 className="font-medium">导入模式说明：</h4>
              <div className="space-y-2 text-sm">
                <div className="flex items-start gap-2">
                  <CheckCircleOutlined className="text-green-500 mt-0.5" />
                  <div>
                    <strong>覆盖导入：</strong>完全替换当前配置
                  </div>
                </div>
                <div className="flex items-start gap-2">
                  <ExclamationCircleOutlined className="text-orange-500 mt-0.5" />
                  <div>
                    <strong>合并导入：</strong>只更新有变化的配置项，保留现有配置
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}
      </Modal>
    );
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h4 className="text-sm font-medium text-gray-700">配置管理</h4>
      </div>

      <div className="flex gap-3">
        <Button
          icon={<DownloadOutlined />}
          onClick={handleExport}
          loading={isExporting}
          disabled={disabled}
          type="default"
          className="flex-1"
        >
          导出配置
        </Button>

        <Upload
          accept=".json"
          showUploadList={false}
          beforeUpload={handleFileSelect}
          disabled={disabled}
        >
          <Button
            icon={<UploadOutlined />}
            disabled={disabled}
            type="default"
            className="flex-1"
          >
            导入配置
          </Button>
        </Upload>
      </div>

      <Alert
        message="配置管理说明"
        description={
          <div className="text-xs space-y-1">
            <div>• <strong>导出配置：</strong>将当前配置保存为 JSON 文件，便于备份和迁移</div>
            <div>• <strong>导入配置：</strong>从 JSON 文件恢复配置，支持覆盖和合并模式</div>
            <div>• 配置文件包含 API Key 等敏感信息，请妥善保管</div>
          </div>
        }
        type="info"
        showIcon
      />

      {renderPreviewModal()}
    </div>
  );
};